import {
  AiFillWechat,
  AiOutlineAlipayCircle,
  AiOutlineLock,
  AiOutlineQq,
  AiOutlineUser,
} from 'react-icons/ai';
import { Button, Checkbox, Form, Input, message, Modal, Space, Tabs } from 'antd';
import React, { useState } from 'react';
import QrCode from 'qrcode.react';
import { useHistory } from 'react-router-dom';
import orgCtrl from '@/ts/controller';
import { kernel } from '@/ts/base';
import { getResouces } from '@/config/location';

const PassportLogin: React.FC<{ to: (flag: string) => void }> = ({ to }) => {
  const history = useHistory();
  const resources = getResouces();
  const [loading, setLoading] = React.useState(false);
  const flexStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'end',
  };
  const AccountLogin: React.FC = () => {
    const [form] = Form.useForm();
    const [open, setOpen] = useState<boolean>();
    const [codeType, setCodeType] = useState<string>();
    const [account, setAccount] = useState<string>();
    const [isNew, setIsNew] = useState<boolean>(true);
    const [password, setPassword] = useState<string>();
    const [dynamicId, setDynamicId] = useState<string>();
    const [dynamicCode, setDynamicCode] = useState<string>();
    const [optUrl, setOtpUrl] = useState<string>();
    const getDynamicCode = async () => {
      if (account && account.length > 0) {
        if (!/(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/.test(account)) {
          message.warn('请输入正确的手机号');
          return false;
        }
        const res = await orgCtrl.auth.dynamicCode({
          account: account,
          platName: resources.platName,
          dynamicId: '',
          isNew: false,
        });
        if (res.success && res.data) {
          setDynamicId(res.data.dynamicId);
          setIsNew(res.data.isNew);
        }
      }
    };

    var loadTwoFactorVerifications = () => {
      return [
        {
          key: 'sms',
          label: `短信口令`,
          children: (
            <Space direction="vertical" size={16}>
              <div>短信验证码的编号为：{dynamicId}</div>
              <Space direction="horizontal" size={0}>
                <Input
                  required
                  size="large"
                  name="dynamicCode"
                  status={isNew ? '' : 'warning'}
                  prefix={<AiOutlineLock />}
                  placeholder={`请输入短信口令`}
                  onChange={(e: any) => {
                    setDynamicCode(e.target.value);
                  }}
                />
                <Button
                  disabled={dynamicId != undefined}
                  size="large"
                  type="primary"
                  onClick={getDynamicCode}>
                  获取验证码
                </Button>
              </Space>
              {!isNew && <div>[请从以往短信验证码中获取该编号的验证码]</div>}
            </Space>
          ),
        },
        {
          key: 'opt',
          label: `动态口令`,
          children: (
            <>
              {optUrl != undefined && optUrl!.length > 0 && (
                <>
                  <label>
                    你可使用第三方 TOTP
                    身份验证应用扫描下方二维码。扫描成功后会生成一次性密码（ 口令
                    ）。常见的 TOTP身份验证应用有: 1Password、 Authy、Microsoft
                    Authenticator 等。 请使用 TOTP 身份验证应用扫描下方二维码:
                  </label>
                  <br />
                  <QrCode
                    level="H"
                    size={250}
                    fgColor={'#204040'}
                    value={optUrl}
                    imageSettings={{
                      width: 60,
                      height: 60,
                      excavate: true,
                      src: '',
                    }}
                  />
                </>
              )}
              <Space direction="vertical" size={16}>
                <Space direction="horizontal" size={0}>
                  <div></div>
                  <Input
                    required
                    size="large"
                    name="dynamicCode"
                    prefix={<AiOutlineLock />}
                    onChange={(e: any) => {
                      setDynamicCode(e.target.value);
                    }}
                    placeholder={`请输入动态口令`}
                  />
                </Space>
              </Space>
            </>
          ),
        },
      ];
    };

    return (
      <>
        <Form
          form={form}
          onFinish={async ({ account, password }) => {
            if (account && password) {
              setAccount(account);
              setPassword(password);
              const res = await orgCtrl.auth.verifyPwd({
                account: account,
                password: password,
              });
              setOpen(res.success);
              setOtpUrl(res.data);
              setDynamicCode(undefined);
              setDynamicId(undefined);
            } else {
              message.warning('请填写账号、密码 ！');
            }
          }}>
          <Form.Item
            name="account"
            rules={[{ required: true, message: '请输入用户名/手机号' }]}>
            <Input
              size="large"
              prefix={<AiOutlineUser />}
              placeholder="请输入用户名/手机号"
            />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password
              size="large"
              prefix={<AiOutlineLock />}
              placeholder="请输入密码"
            />
          </Form.Item>
          <Form.Item>
            <div style={flexStyle}>
              <Checkbox>记住密码</Checkbox>
              <Button type="link" onClick={() => to('forget')}>
                忘记密码
              </Button>
            </div>
          </Form.Item>
          <Form.Item>
            <Button
              block
              loading={loading}
              type="primary"
              size="large"
              htmlType="submit"
              className="ogo-login-button">
              登录
            </Button>
          </Form.Item>
          <Form.Item>
            <div style={flexStyle}>
              <Button type="link" onClick={() => to('register')}>
                注册用户
              </Button>
              <Button
                type="link"
                onClick={() => {
                  history.push('/download');
                }}>
                下载移动端
              </Button>
            </div>
          </Form.Item>
        </Form>
        <Modal
          width={450}
          title={'双因子登录'}
          open={open}
          okButtonProps={{ autoFocus: true }}
          footer={
            <Button
              block
              type="primary"
              size="large"
              onClick={async () => {
                if (dynamicCode && account) {
                  const res = await orgCtrl.auth.login({
                    account: account,
                    password: password,
                    dynamicId: dynamicId,
                    dynamicCode: dynamicCode,
                  });
                  if (res.success) {
                    history.push('/home');
                    if (!localStorage.getItem('userRandomBg') && !res.data.target.icon) {
                      const randomBg = ['blue', 'green', 'red', 'orange'][
                        Math.floor(Math.random() * 4)
                      ];
                      localStorage.setItem('userRandomBg', randomBg);
                    }
                    if (res.data.target.icon && localStorage.getItem('userRandomBg')) {
                      localStorage.removeItem('userRandomBg');
                    }
                  }
                } else {
                  message.warning('请填写口令 ！');
                }
              }}>
              登录
            </Button>
          }
          onCancel={() => {
            setOpen(false);
          }}>
          <>
            <Tabs
              defaultActiveKey={codeType}
              items={loadTwoFactorVerifications()}
              onChange={(key) => {
                setDynamicId(undefined);
                setIsNew(true);
                setCodeType(key);
              }}
            />
          </>
        </Modal>
      </>
    );
  };
  const QrCodeLogin: React.FC = () => {
    return (
      <Space direction="vertical" size={32}>
        <div style={{ textAlign: 'center', marginLeft: 50 }}>
          <QrCode
            level="H"
            size={250}
            fgColor={'#204040'}
            value={JSON.stringify({
              location: resources.location,
              platName: resources.platName,
              connectionId: kernel.connectionId,
            })}
            imageSettings={{
              width: 60,
              height: 60,
              excavate: true,
              src: resources.favicon,
            }}
          />
          <div
            style={{
              fontSize: 18,
              fontWeight: 'bold',
              marginTop: 10,
            }}>
            使用移动端扫码登录
          </div>
        </div>
        <div style={flexStyle}>
          <div
            style={{
              fontSize: 26,
              ...flexStyle,
              gap: 10,
              color: '#666666',
              cursor: 'pointer',
            }}>
            <span style={{ fontSize: 14 }}>其它登录方式</span>
            <AiOutlineAlipayCircle />
            <AiFillWechat />
            <AiOutlineQq />
          </div>
          <Button
            type="link"
            onClick={() => {
              history.push('/download');
            }}>
            下载移动端
          </Button>
        </div>
      </Space>
    );
  };
  return (
    <div>
      <Tabs
        size="large"
        items={[
          { label: '账户登录', key: 'account', children: <AccountLogin /> },
          { label: '二维码登录', key: 'qrCode', children: <QrCodeLogin /> },
        ]}
      />
    </div>
  );
};
export default PassportLogin;
